package com.ltw.dreamer.stock.service.impl;

import java.util.List;
import javax.annotation.Resource;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.ltw.dreamer.common.network.Parser;
import com.ltw.dreamer.report.exception.FinancialReportException;
import com.ltw.dreamer.report.util.SeasonDate;
import com.ltw.dreamer.stock.mapper.MarketHistoryMapper;
import com.ltw.dreamer.stock.model.MarketHistory;
import com.ltw.dreamer.stock.model.MarketHistoryExample;
import com.ltw.dreamer.stock.model.Stock;
import com.ltw.dreamer.stock.model.MarketHistoryExample.Criteria;
import com.ltw.dreamer.stock.service.MarketHistoryService;

@Service
public class MarketHistoryServiceImpl implements MarketHistoryService {
	public static final Logger LOGGER = Logger.getLogger(MarketHistoryServiceImpl.class);
		
	@Resource
	private MarketHistoryMapper mapper = null;
	
	@Resource
	private Parser parser = null;
	
	public void updateMarketHistory(Stock stock) {
		if (stock == null) throw new IllegalArgumentException("传入股票参数为空。");
		LOGGER.info("开始更新股票" + stock.getName() + "[" + stock.getCode() + "]历史股价信息>>>>");
		boolean noStop = true;
		SeasonDate seasonDate = new SeasonDate();
		while (noStop) {
			try {
				noStop = updateMarketHistory(stock, seasonDate);
				seasonDate.decrease();
			} catch (FinancialReportException e) {
				LOGGER.warn(e.getLocalizedMessage());
			}
		}
		LOGGER.info("结束更新股票" + stock.getName() + "[" + stock.getCode() + "]历史股价信息>>>>");
	}
	
	public void fixMarketHistoryData(Stock stock) {
		if (stock == null) throw new IllegalArgumentException("传入股票参数为空。");
		LOGGER.info("开始更新股票" + stock.getName() + "[" + stock.getCode() + "]历史股价信息>>>>");
		SeasonDate seasonDate = new SeasonDate();
		while (shouldContinue(seasonDate)) {
			try {
				updateMarketHistory(stock, seasonDate);
				seasonDate.decrease();
			} catch (FinancialReportException e) {
				LOGGER.warn(e.getLocalizedMessage());
			}
		}
		LOGGER.info("结束更新股票" + stock.getName() + "[" + stock.getCode() + "]历史股价信息>>>>");
	}
	private boolean shouldContinue(SeasonDate seasonDate) {
		if (seasonDate.getYear() == 1990) return false;
		return true;
	}

	private boolean updateMarketHistory(Stock stock, SeasonDate seasonDate) throws FinancialReportException {
		LOGGER.info("处理数据，年份：" + seasonDate.getYear() + ", 季度：" + seasonDate.getSeason() + "...");
		List<MarketHistory> marketHistoryList = parser.read(stock.getCode(), seasonDate);
		if (!parser.hasMoreElement()) return false;
		
		for (MarketHistory marketHistory : marketHistoryList)
			mapper.insert(marketHistory);
		return true;
	}

	public List<MarketHistory> queryMarketHistory(String code) {
		MarketHistoryExample example = new MarketHistoryExample();
		Criteria criteria = example.createCriteria();
		criteria.andCodeEqualTo(code);
		example.setOrderByClause("date");
		
		return mapper.selectByExample(example);
	}
}
